package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单(提交订单)
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional // 多表变更，添加事务
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1、查询前端传递的地址簿id对应的地址信息(订单表需要)，并判断是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            //用户地址为空，不能下单
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //2、查询当前用户的购物车数据(订单明细表需要)，并判断是否为空
        Long userId = BaseContext.getCurrentId(); // 获取当前登录用户id
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();
        List<ShoppingCart> carts = shoppingCartMapper.select(shoppingCart);
        if (carts == null || carts.size() == 0) {
            //购物车数据为空，不能下单
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //3、向订单表插入1条数据(需要返回主键id供订单明细表使用)
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);//已有9项数据，还差8项(用户名没有，不填),另5项后续才填
        order.setNumber(String.valueOf(System.currentTimeMillis()));// 订单号
        order.setStatus(Orders.PENDING_PAYMENT);// 订单状态(1待付款)
        order.setUserId(userId);// 下单用户id
        order.setOrderTime(LocalDateTime.now());// 下单时间
        order.setPayStatus(Orders.UN_PAID);// 支付状态(0未支付)
        order.setPhone(addressBook.getPhone());// 手机号(来自地址簿表)
        order.setAddress(addressBook.getDetail());// 地址(来自地址簿表)
        order.setConsignee(addressBook.getConsignee());// 收货人(来自地址簿表)
        orderMapper.insert(order);

        //4、向订单明细表插入多条数据(订单包含的商品)
        List<OrderDetail> orderDetailList = new ArrayList<>();// 采取批量添加
        for (ShoppingCart cart : carts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());// 添入订单id
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        //5、清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(userId);

        //6、返回响应结果(订单id、订单号、订单金额、下单时间)
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付[导]
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 根据当前登录用户id查询openid
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态[导]
     * @param outTradeNo 订单号
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过WebSocket实现来单提醒，向客户端浏览器(项目管理端前台)推送消息
        Map map = new HashMap();
        map.put("type", 1); //消息类型，1表示来单提醒
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 微信端历史订单查询(分页、非必须条件、只展示详情)
     * @param ordersPageQueryDTO page、pageSize、status
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //只查询当前微信用户的订单表数据(需要获取订单id用于查询订单详情)
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        //集合(多个历史订单)套集合(一个订单多个商品)
        List<OrderVO> records = new ArrayList<>();
        if (page != null && page.size() > 0) {
            //遍历订单表数据集合，查询订单详情
            for (Orders orders : page.getResult()) {
                Long ordersId = orders.getId();
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrdersId(ordersId);
                //必须封装到VO对象中，否则前端不显示
                OrderVO orderVO = new OrderVO();
                //OrderVO继承了Orders，其对象可拥有父类成员变量
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                records.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), records);
    }

    /**
     * 管理端订单分页条件查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //带条件查询所有微信用户的订单表数据(查不到数据时page的size=0)
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> records = new ArrayList<>();
        if (page.size() > 0) {
            //遍历订单表数据集合获取订单id，查询订单详情，并将订单表数据与订单详情字符串封装到VO对象中
            for (Orders orders : page.getResult()) {
                //获取订单id
                Long ordersId = orders.getId();
                //查询订单详情
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrdersId(ordersId);
                //将订单详情中的商品名与数量依次拼接为字符串
                StringBuilder stringBuilder = new StringBuilder();
                for (OrderDetail orderDetail : orderDetails) {
                    String s = orderDetail.getName() + "*" +orderDetail.getNumber() + "；";
                    stringBuilder.append(s);
                }
                String orderDishes = stringBuilder.toString();

                //拼接字符串的另一种方法
                /*// 将每一条订单商品信息拼接为字符串（格式：宫保鸡丁*3；）
                List<String> orderDishList = orderDetails.stream().map(x -> {
                    String orderDish = x.getName() + "*" + x.getNumber() + ";";
                    return orderDish;
                }).collect(Collectors.toList());
                // 将该订单对应的所有菜品信息拼接在一起
                String orderDishes = String.join("", orderDishList);*/

                //创建VO对象
                OrderVO orderVO = new OrderVO();
                //拷贝订单表字段相应变量
                BeanUtils.copyProperties(orders, orderVO);
                //加上订单详情字符串
                orderVO.setOrderDishes(orderDishes);

                records.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), records);
    }

    /**
     * 根据订单id查询订单详情(用户端、管理端通用)
     * @param id 订单id
     * @return
     */
    @Override
    public OrderVO getDetails(Long id) {
        //根据订单id查询订单表数据
        Orders orders = orderMapper.getById(id);
        //根据订单id查询订单详情表数据
        List<OrderDetail> details = orderDetailMapper.getByOrdersId(id);
        //封装返回结果
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(details);
        return orderVO;
    }

    /**
     * 微信小程序端取消订单
     * @param id 订单id
     */
    @Override
    public void cancelByUser(Long id) throws Exception {
        //根据订单id查询订单表数据
        Orders orders = orderMapper.getById(id);
        //校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单处于已接单及其后状态(3已接单 4派送中 5已完成)时，不能直接取消【但微信端有bug，发不出请求】
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders newOrders = new Orders();
        //取消待接单状态的订单，需要进行退款
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED) {
            //调用微信支付退款接口
            /*weChatPayUtil.refund(
                    orders.getNumber(),//商户订单号
                    orders.getNumber(),//商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01)//原订单金额
            );*/
            //支付状态改为 2退款
            newOrders.setPayStatus(Orders.REFUND);
        }
        //更新订单状态(6已取消)、取消原因、取消时间
        newOrders.setStatus(Orders.CANCELLED);
        newOrders.setCancelReason("用户取消");
        newOrders.setCancelTime(LocalDateTime.now());
        newOrders.setId(id);
        //更新订单表数据
        orderMapper.update(newOrders);
    }

    /**
     * 管理端取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancelByAdmin(OrdersCancelDTO ordersCancelDTO) {
        //根据订单id查询订单表数据
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());

        //创建更新数据需要的实体类对象
        Orders newOrders = new Orders();
        //需要对已支付订单进行退款操作
        if (orders.getPayStatus() == 1) {
            //调用微信支付退款接口
            /*String refund = weChatPayUtil.refund(
                    orders.getNumber(),//商户订单号
                    orders.getNumber(),//商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01)//原订单金额
            );
            log.info("申请退款：{}", refund);*/
            //支付状态改为 2退款
            newOrders.setPayStatus(Orders.REFUND);
        }
        //更新订单状态(6已取消)、取消原因、取消时间
        newOrders.setStatus(Orders.CANCELLED);
        newOrders.setCancelReason(ordersCancelDTO.getCancelReason());
        newOrders.setCancelTime(LocalDateTime.now());
        newOrders.setId(ordersCancelDTO.getId());
        //更新订单表数据
        orderMapper.update(newOrders);
    }

    /**
     * 微信小程序端再来一单
     * @param id 订单id
     */
    @Override
    public void repetition(Long id) {
        //根据订单id查询订单详情数据
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrdersId(id);

        ShoppingCart shoppingCart = new ShoppingCart();
        // 添加上当前用户id和创建时间
        shoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCart.setCreateTime(LocalDateTime.now());
        //复制订单详情数据，重新存入购物车表
        for (OrderDetail orderDetail : orderDetails) {
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            //加入购物车
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * [管理端]各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        //查询待接单状态[2]订单数量
        ordersPageQueryDTO.setStatus(Orders.TO_BE_CONFIRMED);
        Page<Orders> page1 = orderMapper.pageQuery(ordersPageQueryDTO);
        int size1 = page1.size();
        //查询待派送状态[3]订单数量
        ordersPageQueryDTO.setStatus(Orders.CONFIRMED);
        Page<Orders> page2 = orderMapper.pageQuery(ordersPageQueryDTO);
        int size2 = page2.size();
        //查询派送中状态[4]订单数量
        ordersPageQueryDTO.setStatus(Orders.DELIVERY_IN_PROGRESS);
        Page<Orders> page3 = orderMapper.pageQuery(ordersPageQueryDTO);
        int size3 = page3.size();

        //封装返回结果
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(size1);
        orderStatisticsVO.setConfirmed(size2);
        orderStatisticsVO.setDeliveryInProgress(size3);
        return orderStatisticsVO;
    }

    /**
     * [管理端]拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //根据订单id查询订单表数据
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        //校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //状态为2（待接单）才可以拒单
        if (!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //如果订单已支付，需要退款
        if (orders.getPayStatus() == Orders.PAID) {
            //调用微信支付退款接口
            /*String refund = weChatPayUtil.refund(
                    orders.getNumber(),//商户订单号
                    orders.getNumber(),//商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01)//原订单金额
            );
            log.info("申请退款：{}", refund);*/
            //支付状态改为 2退款
            orders.setPayStatus(Orders.REFUND);
        }
        //更新订单状态(6已取消)、拒单原因、订单取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        //更新订单表数据
        orderMapper.update(orders);
    }

    /**
     * [管理端]接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //更新订单状态为已接单
        Orders orders = Orders.builder()
                .status(Orders.CONFIRMED)
                .id(ordersConfirmDTO.getId())
                .build();
        orderMapper.update(orders);
    }

    /**
     * [管理端]派送订单
     * @param id 订单id
     */
    @Override
    public void delivery(Long id) {
        //更新订单状态为派送中
        Orders orders = Orders.builder()
                .status(Orders.DELIVERY_IN_PROGRESS)
                .id(id)
                .build();
        orderMapper.update(orders);
    }

    /**
     * [管理端]完成订单
     * @param id 订单id
     */
    @Override
    public void complete(Long id) {
        //更新订单状态为已完成，添加送达时间
        Orders orders = Orders.builder()
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .id(id)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 微信用户催单
     * @param id 订单id
     */
    @Override
    public void reminder(Long id) {
        //根据微信小程序传递的订单id查询订单
        Orders orders = orderMapper.getById(id);
        //判断订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //通过WebSocket向浏览器推送消息
        Map map = new HashMap();
        map.put("type", 2); //消息类型，2代表用户催单
        map.put("orderId", id); //订单id
        map.put("content", "订单号：" + orders.getNumber()); //前端需要展示的信息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
